package framework.captcha;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 默认的验证码处理器
 */
@Slf4j
public class CaptchaSimple extends CaptchaBase implements CaptchaServlet {

    public CaptchaSimple(Cache cache) {
        super(cache);
    }

    public CaptchaSimple(Cache cache, CaptchaGenerator generator) {
        super(cache, generator);
    }

    @Override
    public void output(HttpServletRequest req, HttpServletResponse resp, String id) throws IOException {
        if (!StringUtils.hasLength(id)) {
            resp.setStatus(400);
            resp.getWriter().write("not set param id");
            return;
        }

        //
        if (this.getCache() == null) {
            resp.setStatus(500);
            resp.getWriter().write("not set cache");
            log.warn("Verification: not set cache");
            return;
        }

        //
        CaptchaInfo captchaInfo = this.newCaptcha(id);

        //
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        //
        resp.setContentType("image/jpeg");
        //
        try (ServletOutputStream outputStream = resp.getOutputStream()) {
            ImageIO.write(captchaInfo.getImage(), "jpeg", outputStream);
        }
    }

}
